import db from '../../config/sqlcfg';
import { AbiItem } from 'web3-utils/types';
import { isUndefined } from 'util';

class EthCoinType {
  
  private static table: string = 'eth_coin_type';

  // 获取合约地址
  static async getEthContractAddressList() {
    let rows = await db.query(`select contract_address from ${this.table} where is_contract = 1 and contract_address is not null`);
    return rows;
  }

  /**
   * 获取代币编号ID
   * @param parame 
   */
  static async getCoinTypeId(parame: string): Promise<number> {
    let rows = await db.query(`select id from ${this.table} where name = '${parame}' or contract_address = '${parame}'`);
    if(isUndefined(rows[0])){
      await Promise.reject(`数据库[${this.table}]表中[${parame}]数据不存在`)
    }
    return rows[0].id;
  }


  /**
   * 币种总量增加
   * @param {number} coinTypeId
   * @param {(number|string)} amount
   * @returns
   * @memberof EthCoinType
   */
  static async coinAmountIncrease(coinTypeId: number, amount: number|string) {
    let save = await db.query(`update ${this.table} set amount = amount + ${amount} where id = ${coinTypeId}`);
    return save;
  }

  
  /**
   * 获取合约abiJSON
   * @param {string} contractAddress
   * @returns {Promise<AbiItem>}
   * @memberof EthCoinType
   */
  static async getContractAbiJSON(contractAddress:string): Promise<AbiItem> {
    let raw = await db.query(`select abi from ${this.table} where \`contract_address\` = '${contractAddress}' limit 1`);
    const abi: AbiItem = JSON.parse(raw[0].abi);
    if(isUndefined(raw[0])){
      await Promise.reject(`数据库[${this.table}]表中[${contractAddress}]数据不存在`)
    }
    return abi;
  }


  /**
   * 获取代币小数点
   * @static
   * @param {string} contractAddress
   * @returns {Promise<number>}
   * @memberof EthCoinType
   */
  static async getContractDecimal(contractAddress: string): Promise<number>  {
    let raw = await db.query(`select \`decimal\` from ${this.table} where \`contract_address\` = '${contractAddress}' limit 1`);
    const decimal: number = raw[0].decimal;
    if(isUndefined(raw[0])){
      await Promise.reject(`数据库[${this.table}]表中[${contractAddress}]数据不存在`)
    }
    return decimal;
  }


  /**
   * 获取代币名称
   * @static
   * @param {string} contractAddress
   * @returns {Promise<string>}
   * @memberof EthCoinType
   */
  static async getContractName(contractAddress: string): Promise<string> {
    let raw = await db.query(`select \`name\` from ${this.table} where \`contract_address\` = '${contractAddress}' limit 1`);
    if(isUndefined(raw[0])){
      await Promise.reject(`数据库[${this.table}]表中[${contractAddress}]数据不存在`)
    }
    return raw[0].name;
  }
}

export default EthCoinType;
